package com.sumer.brain.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumer.brain.common.utils.StringUtils;
import com.sumer.brain.sys.mapper.SysRoleMapper;
import com.sumer.brain.sys.model.entity.SysMenu;
import com.sumer.brain.sys.model.resp.MetaVo;
import com.sumer.brain.sys.model.resp.SysMenuResp;
import com.sumer.brain.sys.service.SysMenuService;
import com.sumer.brain.sys.mapper.SysMenuMapper;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    private final SysMenuMapper sysMenuMapper;

    private final SysRoleMapper sysRoleMapper;

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        return sysMenuMapper.getMenusByUserId(userId);
    }

    @Override
    public List<SysMenuResp> buildMenuTree(List<SysMenu> menus) {
        if (Collections.isEmpty(menus)) {
            return null;
        }
        // 将menus转换为SysMenuResp
        List<SysMenuResp> menuRespLis = BeanUtil.copyToList(menus, SysMenuResp.class);
        return buildMenuTree(menuRespLis, 0L);
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        return sysMenuMapper.selectMenuListByRoleId(roleId);
    }

    private List<SysMenuResp> buildMenuTree(List<SysMenuResp> menus, Long parentId) {
        List<SysMenuResp> menuRespList = new ArrayList<>();
        menus.forEach(menu -> {
            if (parentId.equals(menu.getParentId())) {
                menu.setChildren(buildMenuTree(menus, menu.getMenuId()));
                menu.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), null));
                menu.setName(getRouteName(menu));
                menu.setComponent((StringUtils.isEmpty(menu.getComponent()) && menu.getParentId() == 0L) ? "Layout" : menu.getComponent());
                menuRespList.add(menu);
            }
        });
        return menuRespList;
    }

    private String getRouteName(SysMenuResp menu) {
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            return StringUtils.EMPTY;
        }
        return getRouteName(menu.getRouteName(), menu.getPath());
    }

    public String getRouteName(String name, String path) {
        String routerName = StringUtils.isNotEmpty(name) ? name : path;
        return StringUtils.capitalize(routerName);
    }

    private boolean isMenuFrame(SysMenuResp menu) {
        return menu.getParentId().intValue() == 0 && "C".equals(menu.getMenuType()) && menu.getIsFrame() == 1;
    }
}




